package vertx;

import io.vertx.config.ConfigRetriever;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.BodyHandler;
import io.vertx.mysqlclient.MySQLConnectOptions;
import io.vertx.mysqlclient.MySQLPool;
import io.vertx.sqlclient.*;

import java.util.ArrayList;

/**
 * @author 今何许
 * @date 2021-01-11 16:32
 */
public class ConfigVerticle extends AbstractVerticle {
  //配置连接参数
  MySQLConnectOptions connectOptions;

  //配置连接池 Pool options
  PoolOptions poolOptions = new PoolOptions()
    .setMaxSize(5);

  // Create the client pool
  MySQLPool client;

  @Override
  public void start(Promise<Void> startPromise) throws Exception {


    //第一步实例化ConfigRetriever
    ConfigRetriever retriever = ConfigRetriever.create(vertx);

    retriever.getConfig(ar -> {
      if (ar.failed()) {
        // Failed to retrieve the configuration
      } else {
        JsonObject config = ar.result();
        connectOptions= new MySQLConnectOptions()
          .setPort(Integer.parseInt(config.getValue("port").toString()))
          .setHost(config.getString("host"))
          .setDatabase(config.getString("dataBase"))
          .setUser(config.getString("user"))
          .setPassword(config.getString("password"));
        //创建一个数据库连接
        client = MySQLPool.pool(vertx, connectOptions, poolOptions);

        // Create a Router
        Router router = Router.router(vertx);
        //获取body参数，添加这句话
        router.route().handler(BodyHandler.create());


        //根据id查询
        router.route("/query/:id").handler(req -> {
          String id = req.request().getParam("id");
          client.getConnection(arr1 -> {
            if (arr1.succeeded()) {
              SqlConnection connection = arr1.result();
              connection.preparedQuery("select * from user where id=?")
                .execute(Tuple.of(id), arr2 -> {
                  connection.close();
                  if (arr2.succeeded()) {
                    ArrayList<JsonObject> list = new ArrayList<>();
                    RowSet<Row> rows = arr2.result();
                    rows.forEach(row -> {
                      JsonObject entries = new JsonObject();
                      entries.put("id", row.getValue("id"))
                        .put("name", row.getValue("name"));
                      list.add(entries);
                    });
                    req.response().putHeader("content-type", "text/json")
                      .end(list.toString());
                  } else {
                    req.response().putHeader("content-type", "text/json")
                      .end(arr2.cause().toString());
                  }
                });
            } else {

            }
          });
        });


        //绑定路由
        vertx.createHttpServer().requestHandler(router).listen(8888, http -> {
          if (http.succeeded()) {
            startPromise.complete();
            System.out.println("HTTP server started on port 8888");
          } else {
            startPromise.fail(http.cause());
          }
        });
      }
    });


  }
}
